package com.gdpu.service.impl;

import com.gdpu.bo.UmsAdminDetail;
import com.gdpu.mapper.UmsAdminMapper;
import com.gdpu.model.UmsAdmin;
import com.gdpu.model.UmsAdminExample;
import com.gdpu.model.UmsMember;
import com.gdpu.service.UmsAdminService;
import com.gdpu.utils.JwtTokenUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.authentication.PasswordEncoderParser;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author:weiming
 * @Date:2021/6/13
 */
@Service
public class UmsAdminServiceImpl implements UmsAdminService, UserDetailsService {
    @Autowired
    private UmsAdminMapper umsAdminMapper;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private PasswordEncoder passwordEncoder ;

    PasswordEncoder passwordEncoder(){return  new BCryptPasswordEncoder(); }
    @Override
    public String login(String username, String password) {
        String token = null;
        //获取用户对象
        UserDetails userDetails = loadUserByUsername(username);
        //加密密码后比较
        String encode = passwordEncoder().encode("123456");
        if (!passwordEncoder().matches(password, userDetails.getPassword())) {
            return token;
        }
        token = jwtTokenUtil.generateToken(userDetails);
        return token;
    }

    @Override
    public UserDetails loadUserByUsername(String username) {
        //需要获取账号密码和权限
        //UmsAdmin umsAdmin = umsAdminMapper.loadUserByUsername(username);
        UmsAdminExample example = new UmsAdminExample();
        example.createCriteria().andUsernameEqualTo(username);
        List<UmsAdmin> umsAdmins = umsAdminMapper.selectByExample(example);
        if (umsAdmins.isEmpty()){
            throw new UsernameNotFoundException("用户名不存在");
        }
        UmsAdminDetail umsAdmin = new UmsAdminDetail();
        BeanUtils.copyProperties(umsAdmins.get(0),umsAdmin);
        return  umsAdmin;
    }

    @Override
    public int regist(String username, String password) {
        return 0;
    }

}
